package com.kobeliu.entity;

import java.util.PriorityQueue;
import java.util.Queue;

/**
 * @Author: Kobe_Liu
 * @Date: 2021/12/24 10:04
 */
public class Demo_89_No1705 {

    public static void main(String[] args) {

        int[] apples = new int[]{3,1,1,0,0,2};
        int[] days = new int[]{3,1,1,0,0,2};
        System.out.println(eatenApples(apples,days));
    }

    public static int eatenApples(int[] apples, int[] days) {

        //贪心，每次拣最烂的吃
        int n = apples.length;
        int i = 0;
        int ans = 0;
        Queue<int[]> queue = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));
        while(i<n){
            if(apples[i]>0){
                queue.add(new int[]{apples[i],i+days[i]});
            }

            while(!queue.isEmpty() && queue.peek()[1]<=i){
                //清除过期的苹果
                queue.poll();
            }

            //几天吃的苹果
            if(!queue.isEmpty()){
                ans += 1;
                if(--queue.peek()[0]==0){
                    queue.poll();
                }
            }
            i++;
        }
        //过了期限后
        do{
            while(!queue.isEmpty() && queue.peek()[1]<i){
                //清除过期的苹果
                queue.poll();
            }
            if(!queue.isEmpty()){
                //最快烂的苹果有queue.peek()[0]个
                //期限还有queue.peek()[1]-i天
                //两个取最小值，然后弹出
                int limit = Math.min(queue.peek()[0],queue.peek()[1]-i);
                ans += limit;
                i += limit;
                queue.poll();
            }
        }while(!queue.isEmpty());
        return ans;
    }
}
